package apii.servlet.prof;

import static apii.servlet.prof.ProfUtils.finishResponse;
import static apii.servlet.prof.ProfUtils.getSessionProf;
import static apii.servlet.prof.ProfUtils.homeResponse;
import static apii.servlet.prof.ProfUtils.redirectToException;
import static apii.servlet.prof.ProfUtils.redirectToLogin;
import static apii.servlet.prof.ProfUtils.startResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import apii.server.ServerThings;
import apii.servlet.ServletUtils;

/**
 * Servlet implementation class ProfHomeServlet
 */
// assigned by root address: -
// assigned by web.xml address: /prof/*
public class ProfRootServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final String PROF_PREFIX = "/prof";
	private static final String SUBJECTS = "subjects";

	public static final String DISCIPLINE_ID = "discipline_id";
	public static final String LAB_ID = "lab_id";
	public static final String GROUP_ID = "group_id";
	public static final String STUD_ID = "stud_id";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ProfRootServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doProfService(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doProfService(request, response);
	}

	private void doProfService(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=utf-8");
		try (Connection c = ServerThings.getThings().getConnection();) {
			ProfData profData = getSessionProf(c, request);
			if (profData == null) {
				redirectToLogin(response);
				return;
			}
			String requestUri = request.getRequestURI();
			String fullPrefix = ServletUtils.PREFIX + PROF_PREFIX;
			if (!requestUri.startsWith(fullPrefix)) {
				redirectToLogin(response);
				return;
			}
			String filteredUri = requestUri.substring(fullPrefix.length());
			if (!filteredUri.matches("(/[a-z[0-9[_]]]+)*/?")) {
				redirectToLogin(response);
				return;
			} else {
				if ((filteredUri.length() > 0)
						&& (filteredUri.charAt(0) == '/')) {
					filteredUri = filteredUri.substring(1);
				}
				String[] tokens = filteredUri.split("/");
				doUrlHandling(request, response, profData, tokens);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			redirectToException(response);
		}
	}

	private void doUrlHandling(HttpServletRequest request,
			HttpServletResponse response, ProfData profData, String[] tokens)
			throws ServletException, IOException {
		if ((tokens.length == 0) // адрес /prof или /prof/
				|| ((tokens.length == 1) && tokens[0].equals(""))) {
			request.getRequestDispatcher("/prof_home").forward(request,
					response);
		} else {
			if (tokens[0].equals(SUBJECTS)) {

				// разбираем первую строку после prof:
				// если адрес был /prof/кучу, то разбираем кучу
				if (tokens.length == 1) {
					request.getRequestDispatcher("/prof_subjects").forward(
							request, response);
				} else if (tokens.length == 2) {
					int discId = ServletUtils.getDisciplineId(tokens[1]);
					if (discId != ServletUtils.BAD_DISCIPLINE_URL_ELEMENT) {
						request.setAttribute(DISCIPLINE_ID, discId);
						request.getRequestDispatcher("/prof_view_subject")
								.forward(request, response);
					} else {
						ProfUtils.redirectToLogin(response);
					}
				} else if (tokens.length == 3) {
					int discId = ServletUtils.getDisciplineId(tokens[1]);
					int labId = ServletUtils.getLabId(tokens[2]);
					if (discId != ServletUtils.BAD_DISCIPLINE_URL_ELEMENT
							&& labId != ServletUtils.BAD_LAB_URL_ELEMENT) {
						request.setAttribute(DISCIPLINE_ID, discId);
						request.setAttribute(LAB_ID, labId);
						request.getRequestDispatcher("/prof_view_lab").forward(
								request, response);
					} else {
						ProfUtils.redirectToLogin(response);
					}
				} else if (tokens.length == 4) {
					int discId = ServletUtils.getDisciplineId(tokens[1]);
					int labId = ServletUtils.getLabId(tokens[2]);
					int groupId = ServletUtils.getGroupId(tokens[3]);
					if (discId != ServletUtils.BAD_DISCIPLINE_URL_ELEMENT
							&& labId != ServletUtils.BAD_LAB_URL_ELEMENT
							&& groupId != ServletUtils.BAD_GROUP_URL_ELEMENT) {
						request.setAttribute(DISCIPLINE_ID, discId);
						request.setAttribute(LAB_ID, labId);
						request.setAttribute(GROUP_ID, groupId);
						request.getRequestDispatcher("/prof_view_group")
								.forward(request, response);
					} else {
						ProfUtils.redirectToLogin(response);
					}
				} else if (tokens.length == 5) {
					int discId = ServletUtils.getDisciplineId(tokens[1]);
					int labId = ServletUtils.getLabId(tokens[2]);
					int groupId = ServletUtils.getGroupId(tokens[3]);
					int studId = ServletUtils.getStudId(tokens[4]);
					request.setAttribute(STUD_ID, studId);
					request.setAttribute(DISCIPLINE_ID, discId);
					request.setAttribute(LAB_ID, labId);
					request.setAttribute(GROUP_ID, groupId);
					if (discId != ServletUtils.BAD_DISCIPLINE_URL_ELEMENT
							&& labId != ServletUtils.BAD_LAB_URL_ELEMENT
							&& groupId != ServletUtils.BAD_GROUP_URL_ELEMENT
							&& studId != ServletUtils.BAD_STUD_URL_ELEMENT) {
						request.getRequestDispatcher("/prof_view_stud").forward(request, response);
					} else {
						ProfUtils.redirectToLogin(response);
					}
				} else {
					ProfUtils.redirectToLogin(response);
				}
			} else {
				redirectToLogin(response);
				return;
			}
		}
	}
}
